<template>
  <div class="flex flex-col gap-1.25rem">
    <battle-item
      v-for="(battle, idx) in battles"
      :key="battle?.id || idx"
      :battle="battle || {}"
      :loading="loading"
    />
  </div>
</template>

<script lang="tsx" setup>
import { ElMessageBox } from "element-plus";

import { getBattlesList, joinBattle } from "@/api/battles";
import BattleItem from "@/components/BattleItem/battleItem.vue";
import { useAuth } from "@/store/auth";

import type { BattlesExpose } from "./battles";
import { battlesProps } from "./battles";

const props = defineProps(battlesProps);

const isDestory = ref(false);
const timer = ref<number>();
const loading = ref(false);
const battleList = ref<API.Battles.BattleItem[]>([]);
const count = ref(5);
const isPopup = ref(false);

const router = useRouter();
const auth = useAuth();

const battles = computed(() => {
  if (loading.value) {
    return new Array(props.showSize).fill(0);
  }
  return battleList.value;
});

async function getBattles() {
  window.clearTimeout(timer.value);
  const request = props.request || getBattlesList;
  const result = await request(props.params);
  if (result) {
    battleList.value = result?.list || [];
    count.value--;
    if (count.value === 0) {
      if (
        result.invent_battle_cost_amount !== "0" &&
        result.invent_battle_cost_amount !== "" &&
        isPopup.value === false
      ) {
        isPopup.value = true;
        ElMessageBox.confirm(
          `Invite you to join the battle, cost $${result.invent_battle_cost_amount}`,
          "",
          {
            confirmButtonText: "Confirm",
            cancelButtonText: "Cancel",
            cancelButtonClass: "el-button--info",
            type: "success",
            callback: async (res) => {
              if (res === "confirm") {
                const joinResult = await joinBattle({
                  battle_id: result?.invent_battle_id,
                });
                if (joinResult?.battle_id) {
                  auth.getUserAssets();
                  router.push(`/battles/${joinResult?.battle_id}`);
                }
              }
              count.value = 60;
              isPopup.value = false;
            },
          }
        );
      }
      count.value = 60;
    }
  }

  if (isDestory.value) {
    return;
  }

  timer.value = window.setTimeout(() => {
    getBattles();
  }, props.diffRequestSeconds * 1000);
}

async function getInitBattles() {
  loading.value = true;
  await getBattles();
  loading.value = false;
}

onBeforeMount(() => {
  getInitBattles();
});

onBeforeUnmount(() => {
  isDestory.value = true;
  window.clearTimeout(timer.value);
});

defineExpose<BattlesExpose>({
  resetQuery: () => {
    window.clearTimeout(timer.value);
    battleList.value = [];
    getInitBattles();
  },
});
</script>
